package com.chipcoo.sms.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by Administrator on 2016/4/29.
 */
public class SendCloudSMSImpl {
    private String smsUser,smsKey;
    public SendCloudSMSImpl(){
        smsUser="chipwing_test_1Gg7dK";
        smsKey = "zahf3MqjpTjqJnlxsazyPqVeS2A7U4xW";
    }

    private HttpPost createHttpPost(String url,int templateID, Map<String,String> vars, String phones)throws UnsupportedEncodingException {
        Map<String,String> params = new HashMap<String,String>();
        params.put("smsUser", this.smsUser);
        params.put("templateId",String.valueOf(templateID));
        //params.put("msgType", "0");
        params.put("phone", phones);
        if(null!=vars&&!vars.isEmpty())
            params.put("vars", JSON.toJSONString(vars));

        // 对参数进行排序
        Map<String, String> sortedMap = new TreeMap<String, String>(new Comparator<String>() {
            @Override
            public int compare(String arg0, String arg1) {
                // 忽略大小写
                return arg0.compareToIgnoreCase(arg1);
            }
        });
        sortedMap.putAll(params);

        // 计算签名
        StringBuilder sb = new StringBuilder();
        sb.append(smsKey).append("&");
        for (String s : sortedMap.keySet()) {
            sb.append(String.format("%s=%s&", s, sortedMap.get(s)));
        }
        sb.append(smsKey);
        String sig = DigestUtils.md5Hex(sb.toString());
        // 将所有参数和签名添加到post请求参数数组里
        List<NameValuePair> postparams = new ArrayList<NameValuePair>();
        for (String s : sortedMap.keySet()) {
            postparams.add(new BasicNameValuePair(s, sortedMap.get(s)));
        }
        postparams.add(new BasicNameValuePair("signature", sig));

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(postparams, "utf8"));
        return  httpPost;

    }
    private void executePost(HttpPost httpPost)throws IOException{
        CloseableHttpClient httpClient = HttpClients.createDefault();


        HttpResponse response = httpClient.execute(httpPost);
        // 处理响应
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 正常返回, 解析返回数据
            String szReturned = EntityUtils.toString(response.getEntity());
        } else {
            System.err.println("error");
        }
        httpPost.releaseConnection();
    }

    public void sendTemplate(int templateId, Map<String,String> vars, String...phones){
        StringBuilder rcpt_to = new StringBuilder();
        for(int i=0;i<phones.length;i++){
            String phone = phones[i].trim();
            if(phone.length()>0){
                rcpt_to.append(phone);
                rcpt_to.append(',');
            }
        }
        if(rcpt_to.length()==0){

        }else{
            rcpt_to.deleteCharAt(rcpt_to.length()-1);
        }
        try {
            executePost(createHttpPost("http://sendcloud.sohu.com/smsapi/send", templateId, vars, rcpt_to.toString()));
        }catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
